<template>
  <div>
    <div class="users-top">
      <el-input v-model="pageInfo.query" placeholder="请输入内容">
        <el-button
          slot="append"
          @click="search"
          icon="el-icon-search"
          type="default"
        ></el-button>
      </el-input>
      <div class="users-top-left">
        <el-button @click="dialogFormVisible = true" type="primary"
          >添加用户</el-button
        >
      </div>

      <!-- 添加用户弹框 -->
      <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
        <!-- rules 添加验证规则 -->
        <el-form :model="form" ref="formName" :rules="rules">
          <el-form-item
            label="用户名"
            prop="username"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
            <el-input v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="手机"
            prop="mobile"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="mt20">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="date" label="#" width="48">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 滑块 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeSwitch(scope.row.id, scope.row.mg_state)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="address" min-width="130" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editUserInfo(scope.row.id)"
              circle
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="open(scope.row.id)"
              circle
            ></el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-s-tools"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="mt20">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="pageInfo.pagesize"
        layout="sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </div>
    <!-- 编辑弹框 -->
    <el-dialog title="修改用户信息" :visible.sync="dialogEditVisible">
      <el-form :model="EditForm" :rules="editRules" ref="ruleEdit">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input
            v-model="EditForm.username"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="EditForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="EditForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeEditInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsers,
  addUsers,
  changeUsersState,
  searchUser,
  editUser,
  deleteUser
} from "../../api/user";
export default {
  data() {
    var phoneRef = (rule, value, callback) => {
      let phoneRegExp =
        /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
      let flag = RegExp(phoneRegExp).test(value);
      if (!flag) {
        return callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };

    return {
      // 编辑弹框验证规则
      editRules: {
        email: [{ required: true, trigger: "blur", message: "请输入邮箱" }],
        mobile: [{ required: true, trigger: "blur", message: "请输入手机号" }],
      },
      // 编辑弹框初始数据
      EditForm: {},
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄",
        },
      ],
      pageInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      dialogFormVisible: false,
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "用户名的长度在2～10个字",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "用户名的长度在6～18个字",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入合法邮箱", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: phoneRef, trigger: "blur" },
          // { type: "mobile", message: '请输入合法的手机号码', trigger: 'blur' },
        ],
        //
      },
      formLabelWidth: "120px",
      // 控制编辑弹框显示隐藏
      dialogEditVisible: false,
    };
  },
  created() {
    this.init();
  },
  methods: {
    // 删除提示
    open(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteUser({ id })
          await this.init()
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 提交编辑号的用户信息
    changeEditInfo() {
      this.$refs.ruleEdit.validate(async (flag) => {
        if (!flag) {
          this.$message.error("请输入信息");
        } else {
          await editUser({
            ...this.EditForm,
          });
          this.init();
          this.dialogEditVisible = false;
        }
      });
    },
    // 编辑用户信息
    async editUserInfo(id) {
      let res = await searchUser({
        id,
      });
      this.EditForm = res;
      this.dialogEditVisible = true;
    },
    async init() {
      let res = await getUsers({
        ...this.pageInfo,
      });
      this.tableData = res.users;
    },
    handleSizeChange(val) {
      this.pageInfo.pagesize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.pageInfo.pagenum = val;
      this.init();
    },
    // 搜索
    search() {
      this.init();
    },
    // 添加用户
    addUser() {
      this.$refs.formName.validate(async (flag) => {
        if (flag) {
          await addUsers(this.form);
          await this.init();
          this.dialogFormVisible = false;
        } else {
          this.$message.error("请按照格式来填写");
          return false;
        }
      });
    },
    // 修改用户状态
    async changeSwitch(id, flag) {
      await changeUsersState({
        id,
        flag,
      });
    },
  },
};
</script>

<style lang="scss">
.users-top {
  display: flex;
  > .el-input {
    width: 220px;
  }
  > .el-input__inner {
    width: 200px;
    float: left;
  }
  .users-top-left {
    margin-left: 20px;
  }
}

.el-table {
  font-size: 12px !important;
}
</style>